import glob
import os
import re
from datetime import datetime


# return :: (excessive old files to del, file from last update, file from this update)
def check_filenames(dir, ext, limit):
    fnames = glob.glob(dir + "/*." + ext)
    fnames = sorted(fnames,
                    key=lambda x: datetime.strptime(re.search("([\d]{4}-[\d]{2}-[\d]{2})", x).group(1), '%Y-%m-%d'))
    return fnames[0:len(fnames) - limit] if len(fnames) > limit else None, fnames[-2] if len(fnames) > 1 else None, \
           fnames[-1] if len(fnames) > 0 else None


def delete(path):
    os.remove(path)


# default ext="csv". Save then call this method to keep #files at limit=5.
# Returns the 2 latest files. Ready to compare if Ret[0] exists.
def push(dir, ext="csv", limit=5):
    to_del, update0, update1 = check_filenames(dir, ext, limit)
    if to_del:
        for i in to_del:
            delete(i)
    return update0, update1


if __name__ == "__main__":
    print(push("test"))
